package pl.edu.agh.sius.ws;

import java.io.File;
import java.util.List;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.jws.WebService;
import javax.xml.ws.soap.MTOM;

import pl.edu.agh.sius.gui.model.SharedFilesTableModel;
import pl.edu.agh.sius.schema.simplep2pserver.DownloadRequestWrapper;
import pl.edu.agh.sius.schema.simplep2pserver.DownloadResponseWrapper;
import pl.edu.agh.sius.schema.simplep2pserver.FileInfo;
import pl.edu.agh.sius.schema.simplep2pserver.FilesListWrapper;
import pl.edu.agh.sius.wsdl.simplep2pserver.SimpleP2PServerPortType;

@MTOM(enabled = true, threshold = 0)
@WebService(targetNamespace = "http://sius.agh.edu.pl/wsdl/SimpleP2PServer.wsdl", 
        portName="SimpleP2PServerPort",
        serviceName="SimpleP2PServerService", 
        endpointInterface="pl.edu.agh.sius.wsdl.simplep2pserver.SimpleP2PServerPortType")
public class SimpleP2PServerPortTypeImpl implements SimpleP2PServerPortType{
	
	private SharedFilesTableModel sharedFilesTableModel;
	
	@SuppressWarnings("unchecked")
	@Override
	public FilesListWrapper getFilesList() {
		FilesListWrapper fl = new FilesListWrapper();
		fl.getItems().addAll((List<FileInfo>)(List<?>)sharedFilesTableModel.getAllData());
		return fl;
	}

	@Override
	public DownloadResponseWrapper download(DownloadRequestWrapper resourceId) {
		System.out.print("Download request: ");
		System.out.println(new Long(resourceId.getResourceId()).toString());
		
		DownloadResponseWrapper dw = new DownloadResponseWrapper();
		File file = new File(sharedFilesTableModel.getFileMapping().get(new Long(resourceId.getResourceId())));
		DataHandler dh = new DataHandler(new FileDataSource(file));
		dw.setFile(dh);
		return dw;
	}

	public SharedFilesTableModel getSharedFilesTableModel() {
		return sharedFilesTableModel;
	}

	public void setSharedFilesTableModel(SharedFilesTableModel sharedFilesTableModel) {
		this.sharedFilesTableModel = sharedFilesTableModel;
	}

}
